#!/bin/bash

if [ ! $1 ];then
  echo "need master ip : install_k8s 192.168.1.8"
  exit
fi

source /home/core/.profile
source /etc/environment

K8S_FILE=/etc/systemd/system/kubernetes.service
sudo touch $K8S_FILE
sudo chmod -R 777 $K8S_FILE

sudo cat > $K8S_FILE << EOF
[Unit]
Description=kubernetes
After=flannel.service
Requires=flannel.service

[Service]
Restart=always
RestartSec=5
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker stop kubernetes
ExecStartPre=-/usr/bin/docker kill kubernetes
ExecStartPre=-/usr/bin/docker rm kubernetes
ExecStart=/usr/bin/docker run --name=kubernetes --net=host --privileged \\
  -v /etc/kubernetes:/etc/kubernetes \\
  -v /etc/ssl/certs:/etc/ssl/certs \\
  -v /usr/share/ca-certificates:/usr/share/ca-certificates \\
  -v /var/lib/docker:/var/lib/docker \\
  -v /var/lib/kubelet:/var/lib/kubelet \\
  -v /usr/lib/os-release:/etc/os-release \\
  -v /run:/run \\
  -v /home/core/local/kubernetes/start.sh:/start.sh \\
  ivories/kubernetes:1.0 /start.sh
ExecStop=/usr/bin/docker stop kubernetes
ExecStop=/usr/bin/docker kill kubernetes

[Install]
WantedBy=multi-user.target
EOF

sudo mkdir -p /home/core/local/kubernetes

cat > start.sh << EOF
#!/bin/bash
ln -sf /run/docker.pid /run/docker/libcontainerd/docker-containerd.pid

/hyperkube apiserver \
--insecure-bind-address=0.0.0.0 --insecure-port=8080 \
--etcd-servers=http://${LAN_IP}:2379 --logtostderr=true \
--admission-control=NamespaceLifecycle,LimitRanger,SecurityContextDeny,ResourceQuota \
--service-node-port-range=30000-32767 \
--allow-privileged=true \
--service-cluster-ip-range=10.0.1.0/24 \
--advertise-address=${LAN_IP} &

sleep 3s

/hyperkube controller-manager \
--master=${LAN_IP}:8080 \
--logtostderr=true &

/hyperkube scheduler \
--master=${LAN_IP}:8080 \
--logtostderr=true &

/hyperkube proxy \
--hostname-override=${LAN_IP} \
--master=http://${LAN_IP}:8080 \
--logtostderr=true &

/hyperkube kubelet \
--hostname-override=${LAN_IP} \
--api-servers=http://${LAN_IP}:8080 \
--logtostderr=true \
--cluster-dns=10.3.0.10 \
--cluster-domain=cluster.local \
--allow-privileged=true
EOF

sudo mv start.sh /home/core/local/kubernetes/
sudo chmod -R 777 /home/core/local/kubernetes/start.sh

cat > start-slave.sh << EOF
/hyperkube proxy \
--hostname-override=${LAN_IP} \
--master=http://$1:8080 \
--logtostderr=true &

/hyperkube kubelet \
--hostname-override=${LAN_IP} \
--api-servers=http://$1:8080 \
--logtostderr=true \
--cluster-dns=10.3.0.10  --cluster-domain=cluster.local \
--allow-privileged=true
EOF

if [ "${LAN_IP}" == "$1" ];then
  rm -rf start-slave.sh
else
  sudo chmod -R 777 start-slave.sh
  sudo rm -rf /home/core/local/kubernetes/start.sh
  sudo mv start-slave.sh /home/core/local/kubernetes/start.sh
fi

/home/core/docker/shell/waitService kubernetes
